// pages/watch/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    nextPage: true,
    products: {},
    tabStatus:'new'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log('quick index on ready');
    this.loadPage();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({ page: 1, nextPage: true });
    this.loadPage();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log("onPullDownRefresh");
    this.setData({ page: 1 ,nextPage:true});
    this.loadPage();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("onReachBottom");
    this.setData({ page: this.data.page + 1 });
    this.loadPage();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  switchTab: function(e) {
    console.log(e);
    if (this.data.tabStatus != e.currentTarget.dataset.status) {
      this.setData({ 
        tabStatus: e.currentTarget.dataset.status, 
        page: 1,
        nextPage: true });
      console.log(this.data);
      this.loadPage();
    }
  },
  loadPage: function () {
    console.log("loadPage");
    var self = this;

    //已经有数据
    if (!self.data.nextPage) {
      console.log("已经是最后一页");
      return;
    }

    console.log(self.data.products);
    console.log("before setdata");

    app.httpGet('/index.php?r=v1/favorite/index&status='+self.data.tabStatus+'&page=' + self.data.page, {
      success: function (res) {
        console.log(res);
        if (res.data.page < res.data.total_page) {
          self.setData({ nextPage: true });
        }
        else {
          self.setData({ nextPage: false });
        }
        //第一页直接覆盖
        if (self.data.page == 1) {
          self.setData(
            { products: res.data }
          )
        }
        else {
          var oldProducts = self.data.products;
          oldProducts.page = res.data.page;
          oldProducts.total = res.data.total;
          oldProducts.total_page = res.data.total_page;
          oldProducts.items = oldProducts.items.concat(res.data.items);
          self.setData(
            { products: oldProducts }
          )
        }
        console.log(self.data.products);
      }
    });
  },
  updateProductItem: function (product) {
    var oldProducts = this.data.products;
  },
  getProductItem: function (id) {
    var oldProducts = this.data.products;
    if (oldProducts.items) {
      for (var i = 0; i < oldProducts.items.length; i++) {
        var item = oldProducts.items[i];
        if (item.id == id) {
          return item;
        }
      }
    }
    return null;
  },
  updateProducts: function () {
    this.setData({
      products: this.data.products
    });
  },
  onItemClicked: function (e) {
    console.log(e);
    wx.navigateTo({
      url: '/pages/product/view?id=' + e.currentTarget.dataset.id,
    })
  },
  onLoveClicked: function (e) {
    var productId = e.currentTarget.dataset.id;
    var item = this.getProductItem(productId);
    var self = this;

    if (item.is_favorite == true) {
      app.httpDelete('/index.php?r=v1/favorite/index&id=' + productId, {
        success: function (res) {
          console.log(res);
          item.is_favorite = res.data.is_favorite;
          self.updateProducts();
          wx.showToast({
            title: '已取消',
            icon: 'none'
          });
        },
      });
    }
    else {
      app.httpPost('/index.php?r=v1/favorite/index', {
        success: function (res) {
          console.log(res);
          item.is_favorite = res.data.is_favorite;
          self.updateProducts();
          wx.showToast({
            title: '已关注',
          });
        },
      },
        { product_id: productId }
      );
    }
  },
  onBidClicked: function (e) {
    var productId = e.currentTarget.dataset.id;
    var item = this.getProductItem(productId);
    var self = this;

    if (item.next_bid >= item.price) {
      self.onBuyClicked(e);
      return;
    }

    if (item.can_bid) {
      wx.showModal({
        title: '确认要出价吗？',
        confirmText: '出价',
        content: item.next_bid + '',
        success: function (res) {
          if (res.confirm) {
            console.log('bid');
            app.httpPost('/index.php?r=v1/bid/index', {
              success: function (res) {
                console.log(res);
                if (res.code == 200) {
                  item.bid_total = res.data.bid_total;
                  item.next_bid = res.data.next_bid;
                  self.updateProducts();
                }
                else {
                  wx.showToast({
                    title: res.msg,
                  })
                }
              }
            }, {
                product_id: item.id,
                price: item.next_bid
              });
          }
        }
      })
    }
    else {
      wx.showToast({
        title: '尚未开售',
        icon: 'none'
      })
    }
  },
  onBuyClicked: function (e) {
    var productId = e.currentTarget.dataset.id;
    var item = this.getProductItem(productId);
    var self = this;

    if (item.can_bid) {
      wx.showModal({
        title: '确认要出价吗？',
        confirmText: '出价',
        content: item.price + '',
        success: function (res) {
          if (res.confirm) {
            console.log('bid');
            app.httpPost('/index.php?r=v1/bid/buy', {
              success: function (res) {
                console.log(res);
                if (res.code == 200) {
                  item.bid_total = res.data.bid_total;
                  item.next_bid = res.data.next_bid;
                  self.updateProducts();
                  if (res.data.order_id) {
                    var url = "/pages/my/confirm?id=" + res.data.order_id;
                    wx.navigateTo({
                      url: url,
                    })
                  }
                }
                else if (res.code == 100800) {
                  wx.showModal({
                    title: '出价错误',
                    content: '你需要缴纳保证金后才能参与拍卖,请先缴纳保证金',
                    confirmText: '缴纳保证金',
                    success: function (res) {
                      if (res.confirm) {
                        action.payDeposit(self);
                      }
                    }
                  })
                }
                else {
                  wx.showToast({
                    title: res.msg,
                  })
                }
              }
            }, {
                product_id: item.id,
                price: item.next_bid
              });
          }
        }
      })
    }
    else {
      wx.showToast({
        title: '尚未开始',
        icon: 'none'
      })
    }
  }
})